package user

import (
	"cat-collage-backend/constant"
	"cat-collage-backend/internal/model"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"gorm.io/gorm" // 确保已引入GORM
	"net/http"
	"time"
)

func Login(c *gin.Context, db *gorm.DB) {
	username, _ := c.GetPostForm("username")
	password, _ := c.GetPostForm("password")
	browser, _ := c.GetPostForm("browser")
	// 检查用户名和密码是否已输入
	if username == "" || password == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Please provide username and password"})
		return
	}

	var user model.User

	// 根据用户名查询用户
	result := db.Where("username = ?", username).First(&user)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Server error"})
		}
		return
	}

	// 验证密码，这里假设密码是明文存储
	if user.Password != password {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid password"})
		return
	}
	// 登陆成功，下发token
	token := jwt.New(jwt.SigningMethodHS256)
	// 设置claims（声明）
	claims := token.Claims.(jwt.MapClaims)
	claims["user_id"] = user.ID
	claims["time"] = time.Now().UnixNano()
	// 如果是浏览器访问需要设置过期时间 2 天
	if browser == "browser" {
		claims["exp"] = constant.TokenExpireDuration
	}
	// 添加一个随机数到claims，确保每次生成的 token 都不一样
	b := make([]byte, 16) // 生成16字节的随机数
	_, err := rand.Read(b)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error generating random data"})
		return
	}
	claims["rand"] = hex.EncodeToString(b)
	t, err := token.SignedString([]byte(constant.SecretKey))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create token"})
		return
	}
	fmt.Println(user.ID, "user.ID")
	result.Update("token", t)
	c.JSON(http.StatusOK, gin.H{"message": "登录成功", "code": http.StatusOK, "token": t})
}
